package com.gzmu.face.wx.servicet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gzmu.face.wx.msg.resp.TextMessage;
import com.gzmu.face.wx.msg.util.MessageUtil;
import com.gzmu.face.wx.msg.util.SendMsgUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

public class CoreService {
	private static String headurl = "http://jsbx.ynnu.edu.cn/managerlab/";
	private static String picurl1 = "http://jsbx.ynnu.edu.cn/managerlab/res/img/yun.jpg";
	private static String picurl2 = "http://jsbx.ynnu.edu.cn/managerlab/res/img/main.jpg";

	private static String title = "云南师范大学多媒体报修平台";
	/**
	 * @param request
	 * @return xml
	 **/
	public static TextMessage processRequest(String request) {
		String content = null;
		TextMessage textMessage = new TextMessage();
		try {
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			String fromUserName = requestMap.get("FromUserName");
			String toUserName = requestMap.get("ToUserName");
			String msgType = requestMap.get("MsgType");

			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				content = requestMap.get("Content");
			}
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				content = "图片消息";
			}
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				content = "语音消息";
			}
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
				content = "视频消息";
			}
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				content = "位置上报";
			}
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				content = "链接消息";
			}else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");
				System.out.println("------eventType:" + eventType); 
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					content = "欢迎关注报修平台";
				}else{
					String eventKey = requestMap.get("EventKey");
					System.out.println("------EventKey:" + eventKey); 
					if (eventKey.equals("T_REGISTRY")) {					
						SendMsgUtil.sendNewsMsg(title,"点击进入报修登记页面",picurl1,picurl2,headurl+"login.do?teacherid=",fromUserName);
					}else if(eventKey.equals("T_QUERY")){
						SendMsgUtil.sendNewsMsg(title,"点击查询报修进度",picurl1,picurl2,headurl+"tquery.do?teacherid=",fromUserName);
					}else if(eventKey.equals("T_HISTORY")){
						SendMsgUtil.sendNewsMsg(title,"点击查询报修历史记录",picurl1,picurl2,headurl+"tfinish.do?teacherid=",fromUserName);
					}else if(eventKey.equals("R_OVERHAUL")){
						SendMsgUtil.sendNewsMsg(title,"点击查询待维修登记",picurl1,picurl2,headurl+"nomain.do?artisanid=",fromUserName);
					}else if(eventKey.equals("R_FINISH")){
						SendMsgUtil.sendNewsMsg(title,"点击维修历史记录",picurl1,picurl2,headurl+"rhistory.do?artisanid=",fromUserName);
					}					
				}
			}
			if (content==null)
				return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		textMessage.setContent(content);
		return textMessage;
	}

	public static String  getWeatherInform(String cityName){
		//百度天气API
		String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=花溪&output=json&ak=j5j9PlGRf8ECCgXrngZTUplu4RAGAiS1";
		StringBuffer strBuf;
		try {                 
			baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=j5j9PlGRf8ECCgXrngZTUplu4RAGAiS1";					
		} catch (UnsupportedEncodingException e1) {				
			e1.printStackTrace();					
		}

		strBuf = new StringBuffer();
		try{
			URL url = new URL(baiduUrl);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null)
				strBuf.append(line + " ");
			reader.close();
		}catch(IOException e){
			e.printStackTrace(); 
		}		
		return resolveWeatherInf(strBuf.toString());
	}

	private static String resolveWeatherInf(String strPar){
		JSONObject dataOfJson = (JSONObject)JSONObject.toJSON(strPar);
		System.out.println("strPar:"+strPar+"\r\n");
		if (!dataOfJson.equals(null)){
			String date = dataOfJson.getString("date");
			JSONArray results=dataOfJson.getJSONArray("results");
			JSONObject results0=results.getJSONObject(0);
			String addres = results0.getString("currentCity");
			JSONArray weather_data = results0.getJSONArray("weather_data");
			JSONObject OneDayWeatherinfo=weather_data.getJSONObject(0);
	    	String dayData = OneDayWeatherinfo.getString("date");
	    	int beginIndex = dayData.indexOf("：");
			int endIndex = dayData.indexOf(")");
			String weather = dayData.substring(beginIndex+1, endIndex);
			String resStr = "日期："+date+"\r\n地点："+addres+"\r\n天气："+weather;
			
			JSONArray index = results0.getJSONArray("index");
			String dressAdvise = index.getJSONObject(0).getString("des");//穿衣
            String washCarAdvise = index.getJSONObject(1).getString("des");//洗车
            String coldAdvise = index.getJSONObject(3).getString("des");//感冒  
            String sportsAdvise = index.getJSONObject(4).getString("des");//运动  
            String ultravioletRaysAdvise = index.getJSONObject(5).getString("des");//紫外线
            
            resStr = resStr+"\r\n穿衣："+dressAdvise+"\r\n洗车："+washCarAdvise+"\r\n感冒提醒："
            		+coldAdvise+"\r\n运动："+sportsAdvise+"\r\n紫外线："+ultravioletRaysAdvise;
			return resStr;
		}
		return null;		
	}
}
